package com.ccrfid.rmc6.appconfig.filter;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
@Priority(Priorities.USER + 1)
public class CORSResponseFilter implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext reqContext, ContainerResponseContext respContext) throws IOException {
        MultivaluedMap<String, Object> headers = respContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
//        headers.add("Access-Control-Allow-Origin", "http://www.test.com"); //allows CORS requests only coming from www.test.com
        headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia, Authorization");

        MediaType contentType = (MediaType) headers.getFirst("Content-Type");
        if (isEventStream(contentType)) {
            headers.add("X-Accel-Buffering", "no");     //禁用nginx代理缓存
            headers.add("connection", "keep-alive");
            headers.add("cache-control", "no-cache");
        }
    }

    private boolean isEventStream(MediaType contentType) {
        if (contentType != null) {
            if (contentType.getSubtype().equalsIgnoreCase("event-stream")) {
                return true;
            }
        }
        return false;
    }
}
